package com.ruoyi.project.rate.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.rate.Constants;
import com.ruoyi.project.rate.Utils;
import com.ruoyi.project.rate.domain.Kh;
import com.ruoyi.project.rate.domain.KhRule;
import com.ruoyi.project.rate.service.KhRuleService;
import com.ruoyi.project.rate.service.KhService;

@Controller
@RequestMapping("/rate/khRule")
public class KhRuleController extends BaseController {
	private static final String PAGE_FLAG_IN = "IN";
	private static final String PAGE_FLAG_OUT = "OUT";
	private static final String PAGE_FLAG_ALL = "ALL";
	
	@Autowired
	private KhService khService;
	@Autowired
	private KhRuleService khRuleService;

	/**
	 * 进入扣分查询界面
	 * @param khRule
	 * @param mmap
	 * @return
	 */
	@RequestMapping("/khRuleForKf")
	public String khRuleForKf(KhRule khRule, ModelMap mmap) {
		khRule.getKh().setMonthId(Utils.lastMonth());
		mmap.put("khRule", khRule);
		mmap.put("deptList", Utils.level2DeptList());
		return "rate/khRuleListForKf";
	}

	/**
	 * 扣分查询
	 * @param khRule
	 * @return
	 */
	@PostMapping("/listForKf")
	@ResponseBody
	public TableDataInfo listForKf(KhRule khRule) {
		return getDataTable(this.queryForKf(khRule));
	}
	
	@RequestMapping("/export")
	@ResponseBody
	public AjaxResult export(KhRule khRule) {
		List<KhRule> khRuleList = this.queryForKf(khRule);
		
		Map<String, String> khzDictMap = Utils.mapDictByValue(Constants.KHZ);
		
		Workbook wb = new SXSSFWorkbook(500);
		OutputStream out = null;
		String filename = "考核扣分情况_" + khRule.getKh().getMonthId() + UUID.randomUUID().toString() +  ".xlsx";
		try {
			CellStyle horizontalTextWithSongti11 = Utils.styleOfSongti11Horizontal(wb);
			CellStyle horizontalTextWithSongti20 = Utils.styleOfSongti20Horizontal(wb);
			
			Sheet sheet;
			Row row;
			Cell cell;
			CellRangeAddress region;
			int rowIndex = 0;
			int colIndex = 0;
			
			sheet = wb.createSheet();
			wb.setSheetName(0, "考核扣分情况");
			
			// 一级表头 begin
			row = sheet.createRow(rowIndex++);
			row.setHeight((short)(50 * 20));
			colIndex = 0;
			cell = row.createCell(colIndex++);
			cell.setCellValue("鲁中监狱日常工作考核扣分情况汇总表（" + khRule.getKh().getMonthId() + "）");
			cell.setCellStyle(horizontalTextWithSongti20);
			for (int i = 0; i < 12; i++) {
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti20);
			}
			region = new CellRangeAddress(rowIndex-1, rowIndex-1, 0, colIndex - 1);
			sheet.addMergedRegion(region);
			// 一级表头 end
			
			// 二级表头 begin
//			row = sheet.createRow(rowIndex++);
//			row.setHeight((short)(25 * 20));
//			colIndex = 0;
//			cell = row.createCell(colIndex++);
//			cell.setCellValue("单位：" + khRule.getDept().getDeptName());
//			cell.setCellStyle(horizontalTextWithSongti14);
//			region = new CellRangeAddress(rowIndex-1, rowIndex-1, colIndex - 1, colIndex + 1);
//			sheet.addMergedRegion(region);
			// 二级表头 end
			
			// 三级表头 begin
			row = sheet.createRow(rowIndex++);
			row.setHeight((short)(40 * 20));
			colIndex = 0;
			cell = row.createCell(colIndex++);
			cell.setCellValue("业务考核组");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 15 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("考核单位");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 15 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("被考核单位");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 15 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("考核类型");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 10 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("类别");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 15 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("项目");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 30 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("序号");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 10 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("分值");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 10 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("内容及标准");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 30 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("方式");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 20 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("扣分");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 10 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("扣分原因");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 20 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("责任人");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 10 * 256);
			// 三级表头 end
			
			// 扣分项 begin
			// 主办、督办扣分 begin
			for (KhRule _khRule : khRuleList) {
				Kh kh = _khRule.getKh();
				row = sheet.createRow(rowIndex++);
				colIndex = 0;
				
				cell = row.createCell(colIndex++);
				cell.setCellValue(khzDictMap.get(kh.getKhz()));
				cell.setCellStyle(horizontalTextWithSongti11);
				
				cell = row.createCell(colIndex++);
				cell.setCellValue(kh.getCreateDept().getDeptName());
				cell.setCellStyle(horizontalTextWithSongti11);
				
				cell = row.createCell(colIndex++);
				cell.setCellValue(kh.getDept().getDeptName());
				cell.setCellStyle(horizontalTextWithSongti11);
				
				cell = row.createCell(colIndex++);
				if (StringUtils.equals(Constants.KH_TYPE_ZHU, kh.getType())) {
					cell.setCellValue("主办");
				} else if (StringUtils.equals(Constants.KH_TYPE_DU, kh.getType())) {
					cell.setCellValue("督办");
				}
				cell.setCellStyle(horizontalTextWithSongti11);
				
				cell = row.createCell(colIndex++);
				cell.setCellValue(_khRule.getLb());
				cell.setCellStyle(horizontalTextWithSongti11);
				
				cell = row.createCell(colIndex++);
				cell.setCellValue(_khRule.getXm());
				cell.setCellStyle(horizontalTextWithSongti11);
				
				cell = row.createCell(colIndex++);
				cell.setCellValue(_khRule.getXh());
				cell.setCellStyle(horizontalTextWithSongti11);
				
				cell = row.createCell(colIndex++);
				cell.setCellValue(_khRule.getFz());
				cell.setCellStyle(horizontalTextWithSongti11);
				
				cell = row.createCell(colIndex++);
				cell.setCellValue(_khRule.getNr());
				cell.setCellStyle(horizontalTextWithSongti11);
				
				cell = row.createCell(colIndex++);
				cell.setCellValue(_khRule.getFs());
				cell.setCellStyle(horizontalTextWithSongti11);
				
				cell = row.createCell(colIndex++);
				cell.setCellValue(_khRule.getKf().toString());
				cell.setCellStyle(horizontalTextWithSongti11);
				
				cell = row.createCell(colIndex++);
				cell.setCellValue(_khRule.getRemark());
				cell.setCellStyle(horizontalTextWithSongti11);
				
				cell = row.createCell(colIndex++);
				cell.setCellValue(_khRule.getZrr());
				cell.setCellStyle(horizontalTextWithSongti11);
			}
			// 主办、督办扣分 end
			// 扣分项 end
			
			String filepath = Utils.getExportAbsoluteFile(filename);
			File file = new File(filepath);
			if (file.exists() && file.isFile()) {
				file.delete();
			}
			out = new FileOutputStream(filepath);
			wb.write(out);
			return AjaxResult.success(filename);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("导出Excel失败，请联系网站管理员！");
		} finally {
			IOUtils.closeQuietly(wb);
			IOUtils.closeQuietly(out);
		}
	}
	
	/**
	 * 查询扣分情况
	 * @param khRule
	 * @return
	 */
	@ResponseBody
	public List<KhRule> queryForKf(KhRule khRule) {
		if (StringUtils.isBlank(khRule.getPageFlag())) {
			throw new RuntimeException("pageFlag is blank.");
		}
 		if (StringUtils.isBlank(khRule.getKh().getMonthId())) {
			throw new RuntimeException("请选择考核月份.");
		}
		
		if (PAGE_FLAG_ALL.equals(khRule.getPageFlag())) {
			// do nothing.
		} else if (PAGE_FLAG_IN.equals(khRule.getPageFlag())) {
			// 查询当前部门被扣分的情况
			khRule.getKh().setDept(ShiroUtils.getSysDept());
		} else if (PAGE_FLAG_OUT.equals(khRule.getPageFlag())) {
			// 查询当前部门考核其他部门的扣分情况
			khRule.getKh().setCreateDept(ShiroUtils.getSysDept());
		}
		
		// 只查询审核通过的考核信息
		khRule.getKh().setStatus(Constants.KH_STATUS_APPROVED);
		List<Kh> khList = this.khService.findList(khRule.getKh());
		
		// 同一个考核组的放一起
		Collections.sort(khList, new Comparator<Kh>() {
			@Override
			public int compare(Kh o1, Kh o2) {
				return o1.getKhz().compareTo(o2.getKhz());
			}
		});
		
		List<KhRule> khRuleList = new ArrayList<KhRule>();
		BigDecimal zero = new BigDecimal("0");
		
		for (Kh kh : khList) {
			KhRule _kr = new KhRule();
			_kr.setKh(kh);
			_kr.setXh(khRule.getXh());
			List<KhRule> list = this.khRuleService.findList(_kr);
			for (KhRule kr : list) {
				if (kr.getKf() == null || kr.getKf().compareTo(zero) == 0) {
					continue;
				}
				kr.setKh(kh);
				khRuleList.add(kr);
			}
		}
		
		return khRuleList;
	}
}